import java.util.Arrays;

public class Heap {
    public int[] elem;
    public int usedSize;

    public Heap() {
        this.elem =new int[10];
    }

    //对堆初始化
    public void initElem(int[] array){
        for (int i = 0; i < array.length; i++) {
            this.elem[i]=array[i];
            this.usedSize++;
        }
    }

    //创建一个大根堆
    public void creatHeap(){
        for(int parent=(this.usedSize-1-1)/2;parent>=0;parent--){
            shiftDown(parent,usedSize);
        }
    }

    //向下调整
    private void shiftDown(int parent,int usedSize){
        int child=2*parent+1;
        while(child<usedSize){
            if(child+1<usedSize&&elem[child+1]>elem[child]){
                child++;
            }
            if(elem[parent]<elem[child]){
                swap(elem,parent,child);
                parent=child;
                child=2*parent+1;
            }else{
                break;
            }
        }
    }
    //交换方法
    private void swap(int[] elem,int i,int j){
        int tmp=elem[i];
        elem[i]=elem[j];
        elem[j]=tmp;
    }


    //插入数据
    public void offer(int val){
        if (isFull()){
            this.elem= Arrays.copyOf(elem,2*elem.length);
        }
        elem[usedSize]=val;
        shiftUp(usedSize);
        usedSize++;
    }

    //向上调整
    private void shiftUp(int child){
        int parent=(child-1)/2;
        while(parent>=0){
            if(elem[parent]<elem[child]){
                swap(elem,parent,child);
                child=parent;
                parent=(child-1)/2;
            }else {
                break;
            }
        }
    }


    //删除
    public int poll(){
        if (isEmpty()){
            return -1;
        }
        int val=elem[0];
        //一般删去堆顶元素，此时为最大元素，与最后一个元素交换位置
        swap(elem,0,usedSize-1);
        //向下调整
        shiftDown(0,usedSize-1);
        usedSize--;
        return val;
    }

    //取顶端元素
    public int peek(){
        if (isEmpty()){
            return -1;
        }
        return elem[0];
    }


    //判空
    public boolean isEmpty(){
        return usedSize==0;
    }

    //判满
    public boolean isFull(){
        return elem.length==usedSize;
    }
}
